package com.kdzy.lshy.socity_server.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kdzy.lshy.socity_server.common.Constants;
import com.kdzy.lshy.socity_server.common.ExceptionDetailMessage;
import com.kdzy.lshy.socity_server.common.ResultMap;
import com.kdzy.lshy.socity_server.repository.BaseDao;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class AppVersionService extends BaseService {

    @Resource
    private BaseDao baseDao;

    private static final Logger logger = LoggerFactory.getLogger(AppVersionService.class);

    /**
     * App版本号 - 查询最新版本号
     * @param param 包含当前版本号等信息
     * @return 结果集 - 是否需要更新
     */
    public Object getVersion(String param, HttpServletRequest request) {
        if (StringUtils.isBlank(param)) {
            logger.info("param参数为空");
            return ResultMap.creatReault("88", "失败", "参数为空");
        }

        LinkedHashMap<Object, Object> map = null;
        try {
            // 1.解析json数据
            JSONObject jsonObject = JSON.parseObject(param);
            Long stamp = jsonObject.getLong("stamp"); // 时间戳
            Integer version = jsonObject.getInteger("version"); // 版本 0:测试 1:生产
            Integer visitPlat = jsonObject.getInteger("visit_plat"); // 访问平台 0:网页 1:一体机 2:小程序 3:其他 4:app
            Integer visitType = jsonObject.getInteger("visit_type"); // 访问类型 0:测试 1:生产
            Integer isUsed = jsonObject.getInteger("is_used"); // 是否有效 0:有效 1:无效

            String oldAppVersion = (String)jsonObject.get("oldAppVersion"); // 旧的app版本号
            String socityId = (String)jsonObject.get("socityId"); // 社区id

            // 参数非空判断
            if (stamp == null) {
                logger.info("参数stamp为空");
                map = ResultMap.creatReault("88", "失败", "参数为空");
                logger.info("出去《App版本号 - 查询最新版本号》getVersion()方法；出参 = " + JSON.toJSONString(map));
                return map;
            }
            if (version == null) {
                logger.info("参数version为空");
                map = ResultMap.creatReault("88", "失败", "参数为空");
                logger.info("出去《App版本号 - 查询最新版本号》getVersion()方法；出参 = " + JSON.toJSONString(map));
                return map;
            }
            if (isUsed == null) {
                logger.info("参数is_used为空");
                map = ResultMap.creatReault("88", "失败", "参数为空");
                logger.info("出去《App版本号 - 查询最新版本号》getVersion()方法；出参 = " + JSON.toJSONString(map));
                return map;
            }
            if (visitPlat == null) {
                logger.info("参数visit_plat为空");
                map = ResultMap.creatReault("88", "失败", "参数为空");
                logger.info("出去《App版本号 - 查询最新版本号》getVersion()方法；出参 = " + JSON.toJSONString(map));
                return map;
            }
            if (visitType == null) {
                logger.info("参数visit_type为空");
                map = ResultMap.creatReault("88", "失败", "参数为空");
                logger.info("出去《App版本号 - 查询最新版本号》getVersion()方法；出参 = " + JSON.toJSONString(map));
                return map;
            }

            if (StringUtils.isBlank(oldAppVersion)) { // 版本号为空
                logger.info("账号oldAppVersion参数为空");
                map =  ResultMap.creatReault("88", "失败", "参数为空");
                logger.info("出去《App版本号 - 查询最新版本号》getVersion()方法；出参 = " + JSON.toJSONString(map));
                return map;
            }
            if (StringUtils.isBlank(socityId)) { // 社区id为空
                logger.info("账号socityId参数为空");
                map =  ResultMap.creatReault("88", "失败", "参数为空");
                logger.info("出去《App版本号 - 查询最新版本号》getVersion()方法；出参 = " + JSON.toJSONString(map));
                return map;
            }

            // 查询最新的版本号
            String getVersionSql = "SELECT\n" +
                    "\tv.ver_num newVersion,\n" +
                    "\tv.ver_note versionNote,\n" +
                    "\tv.create_time createTime,\n" +
                    "\tv.ver_url  verUrl\n" +
                    "FROM\n" +
                    "\tversion v\n" +
                    "WHERE\n" +
                    "\tv.is_used = 0\n" +
                    "AND v.visit_type = 0\n" +
                    "AND v.version = 0\n" +
                    "AND v.create_time = (\n" +
                    "\tSELECT\n" +
                    "\t\tMAX(create_time)\n" +
                    "\tFROM\n" +
                    "\t\tversion\n" +
                    ")\n" +
                    "AND v.socity_id = '" + socityId + "'";
            List<Map<String, Object>> versionList = baseDao.getAllByCondition(getVersionSql);
            if (versionList == null || versionList.size() == 0 || versionList.size() > 1) {
                logger.info("App版本暂时为空");
                return ResultMap.creatReault("0", "成功", "不需要更新");
            }

            // 获取新的版本号
            String newAppVersion = (String)versionList.get(0).get("newVersion");

            // 比较前台传过来的oldAppVersion和newAppVersion是否一致
            if (StringUtils.equals(oldAppVersion, newAppVersion)) { // 一致
                logger.info("App版本号新旧一致");
                return ResultMap.creatReault("0", "成功", "不需要更新");
            } else {
                logger.info("App版本号新旧不一致");
                // 需要更新，返回最新版本号的相关信息
                map = ResultMap.creatReault("1", "成功", versionList.get(0));
                logger.info("出去《App版本号 - 查询最新版本号》getVersion()方法；出参 = " + JSON.toJSONString(map));
                return map;
            }

        } catch (ClassCastException e) {
            logger.error("异常信息：" + ExceptionDetailMessage.getExceptionDetail(e));
            map = ResultMap.creatReault("98", "失败", "参数类型错误");
            logger.info("出去《App版本号 - 查询最新版本号》getVersion()方法；出参 = " + JSON.toJSONString(map));
            return map;
        } catch (Exception e) {
            logger.error("异常信息：" + ExceptionDetailMessage.getExceptionDetail(e));
            return ResultMap.creatReault("99", "失败", "后台处理异常");
        }

    }
}